package com.huanxing.cloud.common.security.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.huanxing.cloud.common.core.entity.R;
import com.huanxing.cloud.common.security.entity.HuanxingUser;
import com.huanxing.cloud.common.security.service.HuanxingUserDetailsService;
import com.huanxing.cloud.upms.common.entity.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/** @Author lijx @Date 2022/1/26 16:31 */
@Service
public class HuanxingUserDetailsServiceImpl implements HuanxingUserDetailsService {

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    R<SysUser> sysUserR = new R<SysUser>();
    SysUser sysUser = new SysUser();
    sysUser.setId("1");
    sysUser.setUsername("admin");

    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    // 加密
    String encodedPassword = passwordEncoder.encode("123456");
    sysUser.setPassword(encodedPassword);
    String[] roles = {"ADMIN"};
    sysUser.setRoles(roles);
    String[] permissions = {"upms:sysuser:get"};
    sysUser.setPermissions(permissions);
    sysUserR.setData(sysUser);
    return getUserDetails(sysUserR);
  }

  private UserDetails getUserDetails(R<SysUser> result) {
    SysUser user = result.getData();
    Set<String> dbAuthsSet = new HashSet<>();
    if (ArrayUtil.isNotEmpty(user.getRoles())) {
      // 获取角色
      Arrays.stream(user.getRoles()).forEach(roleId -> dbAuthsSet.add("ROLE_" + roleId));
      // 获取资源
      dbAuthsSet.addAll(Arrays.asList(user.getPermissions()));
    }
    Collection<? extends GrantedAuthority> authorities =
        AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
    return new HuanxingUser(
        user.getId(),
        user.getType(),
        "1",
        "",
        user.getUsername(),
        user.getPassword(),
        true,
        true,
        true,
        true,
        authorities);
  }
}
